//
//  AppINI.m
//  storeapp
//
//  Created by huangyi on 12-12-10.
//  Copyright (c) 2012年 ios. All rights reserved.
//

#import "INIObj.h"
#import "NSString+path.h"
#import "iniparser.h"

static NSDictionary* parseIni(NSString *filename){
    if (filename.length) {
        dictionary *ini=iniparser_load(filename.UTF8String);
        NSMutableDictionary *outIni=nil;
        if (ini) {
            outIni=[NSMutableDictionary dictionary];
            int s,ns,k,nk;
            ns=iniparser_getnsec(ini);
            for (s=0; s<ns; s++) {
                char *sec=iniparser_getsecname(ini, s);
                NSString *outSection=[NSString stringWithCString:sec encoding:NSUTF8StringEncoding];
                NSMutableDictionary *iniSection=[NSMutableDictionary dictionary];
                [outIni setValue:iniSection forKey:outSection];
                nk=iniparser_getsecnkeys(ini, sec);
                char **keys=iniparser_getseckeys(ini, sec);
                for (k=0; k<nk; k++) {
                    NSString *outKey=[NSString stringWithCString:keys[k] encoding:NSUTF8StringEncoding];
                    outKey=[outKey substringFromIndex:outSection.length+1];
                    NSString *outValue=[NSString stringWithCString:iniparser_getstring(ini, keys[k], "") encoding:NSUTF8StringEncoding];
                    [iniSection setValue:outValue forKey:outKey];
                }
            }
        }
        iniparser_freedict(ini);
        return outIni;
    }else{
        return nil;
    }
}

static BOOL writeIni(NSString *filename,NSDictionary *inIni){
    if (filename.length && inIni) {
        if (!filename.isWriteable) {
            NSLog(@"readonly:%@ is readonly",filename);
            return NO;
        }
        NSMutableString *buffer=[NSMutableString string];
        NSArray *allSection=[inIni allKeys];
        for (NSString *inSection in allSection) {
            [buffer appendFormat:@"[%@]\n",inSection];
            NSDictionary *sectionChild=[inIni valueForKey:inSection];
            NSArray *allKey=[sectionChild allKeys];
            for (NSString *inKey in allKey) {
                NSString *inValue=[sectionChild valueForKey:inKey];
                [buffer appendFormat:@"%@=%@\n",inKey,inValue];
            }
        }
        NSError *error=nil;
        [buffer writeToFile:filename atomically:YES encoding:NSUTF8StringEncoding error:&error];
        if (error) {
            NSLog(@"%@",error.description);
            return NO;
        }else{
            return YES;
        }
    }else{
        return NO;
    }
}

@interface INIObj ()

@property(nonatomic,strong)NSString *file;
@property(nonatomic,strong)NSMutableDictionary *store;

@end

@implementation INIObj

-(void)dealloc{
    [self save];
}
-(INIObj*)init{
    return [self initINI:nil];
}
+(INIObj*)shared{
    static INIObj *singleton=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *filename=@"app.ini".docPath;
        singleton=[[INIObj alloc] initINI:filename];
    });
    return singleton;
}
-(id)initINI:(NSString*)filename{
    self=[super init];
    if (self) {
        self.file=[NSString stringWithString:filename];
        [self reload];
    }
    return self;
}
-(NSString*)absolutePath{
    return self.file;
}

-(NSString*)section:(NSString*)section key:(NSString*)key{
    NSString *outValue=nil;
    if (section && key) {
        NSMutableDictionary *outSection=[self.store valueForKey:section];
        if (outSection) {
            outValue=[outSection valueForKey:key];
        }
    }
    return outValue;
}
-(BOOL)section:(NSString*)section key:(NSString*)key value:(NSString*)value{
    if (section && key) {
        NSMutableDictionary *outSection=[self.store valueForKey:section];
        if (!outSection) {
            outSection=[NSMutableDictionary dictionary];
            [self.store setValue:outSection forKey:section];
        }
        if (value) {
            [outSection setValue:value forKey:key];
        }else{
            [outSection removeObjectForKey:key];
        }
        return YES;
    }else{
        return NO;
    }
}
-(BOOL)save{
    return writeIni(self.file,self.store);
}
-(BOOL)clear{
    [self.store removeAllObjects];
    return [self save];
}
-(void)reload{
    self.store=[NSMutableDictionary dictionary];
    if (self.file) {
        if (self.file.isFile) {
            NSDictionary *ini=parseIni(self.file);
            [self.store setValuesForKeysWithDictionary:ini];
        }else{
            [self save];
        }
    }
}

@end
